import sys
import threading
import time

from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QScrollArea, QHBoxLayout, QPushButton


class MyWindow(QWidget):
    customSignal = pyqtSignal(str)
    history_msg = list()

    def __init__(self):
        super().__init__()
        self.btn1 = None
        self.hb = None
        self.scroll = None
        self.ql = None
        self.container = None
        self.qb = None
        self.setWindowTitle("多线程")
        self.resize(600, 200)
        self.init_ui()

    def init_ui(self):
        # 整体布局是垂直布局器
        self.container = QVBoxLayout()

        self.ql = QLabel()
        self.ql.resize(400,15)
        self.ql.setWordWrap(True)  # 自动换行
        self.ql.setAlignment(Qt.AlignTop)
        # 创建一个滚动区域
        self.scroll = QScrollArea()
        self.scroll.setWidget(self.ql)

        # 创建一个垂直布局器 用来添加自动滚动条
        self.qb = QVBoxLayout()
        self.qb.addWidget(self.scroll)

        self.btn1 = QPushButton("运行")
        self.btn1.setFixedSize(80, 30)
        # 给按钮绑定槽函数
        self.btn1.clicked.connect(self.btn_click)
        self.customSignal.connect(self.print_hello)
        # 创建一个水平布局器 用来存放按钮
        self.hb = QHBoxLayout()
        self.hb.addStretch(1)
        self.hb.addWidget(self.btn1)
        self.hb.addStretch(1)

        # 垂直布局器 水平布局器 设置到整体的窗口布局中
        self.container.addLayout(self.qb)
        self.container.addLayout(self.hb)
        self.setLayout(self.container)
        pass

    def btn_click(self):
        # 执行work 将结果发送给 self customSignal
        print("hello")
        # 发送消息给customSignal
        for e in range(1, 12):
            self.customSignal.emit("执行中......")
            time.sleep(2)
        pass

    def print_hello(self, msg):
        print(msg)
        self.history_msg.append(msg)
        self.ql.setText("<br/>".join(self.history_msg))
        self.ql.resize(440, self.ql.frameSize().height() + 15)
        self.ql.repaint()  # 更新内容,如果不更新可能没有显示新内容


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())
